

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="XiaoMaDing">
  <meta name="keywords" content="">
  
    <meta name="description" content="背景□ 现象：组内同事负责的支付中心，在与三方支付平台进行对账时，发现本地钱包、三方支付平台的余额对不上 □ 排查：在钱包流水表中发现了异常，存在两条一模一样的流水记录     问题排查经过现象初步定位，是修改钱包余额的代码存在问题，但是钱包余额修改是加了分布式锁的，并且正常运行了很久了，近期没有进行过修改。于是组内成员(也包括我)开始协助排查 1、复现问题：先看是否能复现问题  找到该条记录的，">
<meta property="og:type" content="article">
<meta property="og:title" content="生产事故：事务与锁">
<meta property="og:url" content="http://example.com/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/index.html">
<meta property="og:site_name" content="剑出">
<meta property="og:description" content="背景□ 现象：组内同事负责的支付中心，在与三方支付平台进行对账时，发现本地钱包、三方支付平台的余额对不上 □ 排查：在钱包流水表中发现了异常，存在两条一模一样的流水记录     问题排查经过现象初步定位，是修改钱包余额的代码存在问题，但是钱包余额修改是加了分布式锁的，并且正常运行了很久了，近期没有进行过修改。于是组内成员(也包括我)开始协助排查 1、复现问题：先看是否能复现问题  找到该条记录的，">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/index_img/tran_sync.png">
<meta property="article:published_time" content="2023-07-20T05:21:48.000Z">
<meta property="article:modified_time" content="2023-12-26T03:48:16.419Z">
<meta property="article:author" content="XiaoMaDing">
<meta property="article:tag" content="分布式锁">
<meta property="article:tag" content="事务">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://example.com/index_img/tran_sync.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>生产事故：事务与锁 - 剑出</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.5-a","typing":{"enable":true,"typeSpeed":40,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":4},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":false,"baidu":"e0dcc0c9ab8f117bb83579322e04efb8","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?e0dcc0c9ab8f117bb83579322e04efb8";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 60vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>剑出</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/yuzhou.gif') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="生产事故：事务与锁"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-07-20 13:21" pubdate>
          2023年7月20日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          2k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          17 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">生产事故：事务与锁</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：7 个月前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h1><p>□ 现象：组内同事负责的支付中心，在与三方支付平台进行对账时，发现本地钱包、三方支付平台的余额对不上</p>
<p>□ 排查：在钱包流水表中发现了异常，存在两条一模一样的流水记录</p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2022-05-25_16-30-37.png" srcset="/img/loading.gif" lazyload alt="1" style="zoom:80%;">



<h1 id="问题排查"><a href="#问题排查" class="headerlink" title="问题排查"></a>问题排查</h1><p>经过现象初步定位，是修改钱包余额的代码存在问题，但是钱包余额修改是加了分布式锁的，并且正常运行了很久了，近期没有进行过修改。于是组内成员(也包括我)开始协助排查</p>
<p>1、复现问题：先看是否能复现问题</p>
<ol>
<li>找到该条记录的，接口参数，进行debug，发现结果无误</li>
<li>怀疑是多线程并发导致，使用单元测试，用多线程去压测 （未复现）</li>
</ol>
<p>2、既然业务逻辑没问题，就怀疑分布式锁没锁住了，从下面几个方面排查</p>
<ol>
<li><p>Redis主从切换：怀疑是redis发生了主从切换，导致锁丢失</p>
<p>让运维协助排查，业务动作的前后几天，都未发现有Redis主从切换</p>
</li>
<li><p>详细排查代码：最终发现了问题</p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2022-05-25_16-55-30.png" srcset="/img/loading.gif" lazyload alt="2" style="zoom:80%;">

<p><b></b></p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2022-05-25_17-00-03.png" srcset="/img/loading.gif" lazyload alt="3" style="zoom:80%;"> 

<p>2.1）事务源码：看过Spring事务源码的，都知道是基于AOP实现的，执行流程如下：</p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-18_12-50-04.png" srcset="/img/loading.gif" lazyload alt="4" style="zoom:70%;">   

<p>2.2）问题：目标方法执行完了，锁就释放了，但是此时事务还没提交 （锁的范围 &lt; 事务范围）</p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-18_12-43-17.png" srcset="/img/loading.gif" lazyload alt="5" style="zoom:80%;">    

<p>2.3）并发：如果在A请求，锁释放了，事务还没提交时。B请求又进来了，也能正常进行业务操作</p>
</li>
</ol>
<h1 id="解决"><a href="#解决" class="headerlink" title="解决"></a>解决</h1><p>问题分析清楚了，那就有以下几种解决方案</p>
<h2 id="1、数据库锁"><a href="#1、数据库锁" class="headerlink" title="1、数据库锁"></a>1、数据库锁</h2><p>不要使用基于Redis的分布式锁了，改为使用数据库悲观锁</p>
<p>在<code>changeAmount()</code>方法中，用数据库的悲观锁 (悲观锁在事务提交完成后，才会释放)</p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_12-31-40.png" srcset="/img/loading.gif" lazyload alt="6" style="zoom:80%;">

<p><b></b></p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_12-32-16.png" srcset="/img/loading.gif" lazyload alt="7" style="zoom:80%;">





<h2 id="2、加锁范围调整"><a href="#2、加锁范围调整" class="headerlink" title="2、加锁范围调整"></a>2、加锁范围调整</h2><p>既然问题出在，锁的范围 &lt; 事务范围，那就让锁的范围 &gt;&#x3D; 事务范围即可</p>
<p>改动点：在业务操作的最外层，加分布式锁</p>
<p>考虑：由于历史债务，调用方有很多，所以暂时未采用该方案</p>
<p>□ 伪代码如下：</p>
<figure><div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 收入</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">income</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">final</span> <span class="token class-name">LockInfo</span> lock <span class="token operator">=</span> lockTemplate<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span>lockKey<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 操作钱包、钱包流水</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
        lockTemplate<span class="token punctuation">.</span><span class="token function">releaseLock</span><span class="token punctuation">(</span>lock<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>            
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div></figure>

<figure><div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 转账</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">transfer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">final</span> <span class="token class-name">LockInfo</span> lock <span class="token operator">=</span> lockTemplate<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span>lockKey<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 操作钱包、钱包流水</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
        lockTemplate<span class="token punctuation">.</span><span class="token function">releaseLock</span><span class="token punctuation">(</span>lock<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>  
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div></figure>

<figure><div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 扣减</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">transfer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">final</span> <span class="token class-name">LockInfo</span> lock <span class="token operator">=</span> lockTemplate<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span>lockKey<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 操作钱包、钱包流水</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
        lockTemplate<span class="token punctuation">.</span><span class="token function">releaseLock</span><span class="token punctuation">(</span>lock<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>  
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div></figure>





<h1 id="加锁切面"><a href="#加锁切面" class="headerlink" title="加锁切面"></a>加锁切面</h1><p>这里再提一句，一般分布式锁，我们会封装成1个AOP，使用注解来调用。那在某些使用情况下，也需要注意</p>
<h2 id="1、AOP失效"><a href="#1、AOP失效" class="headerlink" title="1、AOP失效"></a>1、AOP失效</h2><p>加锁AOP的失效，同事务失效的原因一样，如果采用this调用等方式，会导致AOP失效，使用时需要注意</p>
<h2 id="2、AOP优先级"><a href="#2、AOP优先级" class="headerlink" title="2、AOP优先级"></a>2、AOP优先级</h2><p>之前，在其他项目中，我看到有人这样使用：</p>
<figure><div class="code-wrapper"><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@RedisLock</span>
<span class="token annotation punctuation">@Transactional</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doSomething</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 业务操作</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre></div></figure>

<p>因为<code>@Transactional</code>底层一样是使用AOP来实现的，所以也可能会存问题，具体来说就是：</p>
<p>若<code>@RedisLock切面优先级</code> &lt; <code>@Transactional切面优先级</code>，就会导致【锁的范围 &lt; 事务范围】，就会出现上面的问题</p>
<p>那么自定义的AOP切面，和事务的切面，优先级，到底谁高谁低尼？</p>
<br>

<p>1、事务切面优先级</p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_12-49-22.png" srcset="/img/loading.gif" lazyload alt="8" style="zoom:80%;"> 

<p>我们知道事务切面<code>BeanFactoryTransactionAttributeSourceAdvisor</code>，实现了Ordered，但是并未重写该方法</p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_12-51-23.png" srcset="/img/loading.gif" lazyload alt="9" style="zoom:80%;"> 

<p>而<code>AbstractPointcutAdvisor</code>中，如果未指定order，默认为：<code>Ordered.LOWEST_PRECEDENCE</code>也就是最低优先级</p>
<p>2、自定义切面优先级</p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_12-53-32.png" srcset="/img/loading.gif" lazyload alt="10" style="zoom:80%;">

<p>假设我们没有使用<code>@Order</code>，<code>@Aspect</code>最终会被封装为<code>InstantiationModelAwarePointcutAdvisorImpl</code></p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_12-57-51.png" srcset="/img/loading.gif" lazyload alt="11" style="zoom:80%;"> 

<p><b></b></p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_12-59-52.png" srcset="/img/loading.gif" lazyload alt="12" style="zoom:80%;">

<p><b></b></p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_13-00-00.png" srcset="/img/loading.gif" lazyload alt="11" style="zoom:80%;"> 

<p>从源码，我们可以看到，如果不指定Order值，默认为：<code>Ordered.LOWEST_PRECEDENCE</code>也就是最低优先级</p>
<p>3、都是最低优先级，那到底哪个先执行？测试一下，就知道了</p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_13-02-18.png" srcset="/img/loading.gif" lazyload alt="12" style="zoom:80%;">

<p><b></b></p>
<img src="/2023/07/20/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9A%E4%BA%8B%E5%8A%A1%E4%B8%8E%E9%94%81/Snipaste_2023-12-20_13-03-38.png" srcset="/img/loading.gif" lazyload alt="13" style="zoom:80%;"> 

<p>可以看到，事务切面的优先级更高，会先执行。</p>
<p>□ 解决方案：</p>
<ol>
<li><p>在外层方法中加<code>@RedisLock</code>：推荐</p>
</li>
<li><p>给<code>LockRedisAop</code>设置优先级：不推荐</p>
<figure><div class="code-wrapper"><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">1</span>、因为公司一般是封装的公共组件，不太容易更改；即使改了，可能对其他业务造成不可评估的影响
<span class="token number">2</span>、万一哪天优先级被别人改了，可能引发生产事故
<span class="token number">3</span>、维护难度大，需要对Spring源码有一定掌握程度，否则无法预料程序执行结果<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre></div></figure></li>
</ol>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85/" class="category-chain-item">生产事故</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/" class="print-no-link">#分布式锁</a>
      
        <a href="/tags/%E4%BA%8B%E5%8A%A1/" class="print-no-link">#事务</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>生产事故：事务与锁</div>
      <div>http://example.com/2023/07/20/生产事故：事务与锁/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>XiaoMaDing</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年7月20日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/08/05/%E7%B3%BB%E7%BB%9F%E8%AE%BE%E8%AE%A1%EF%BC%9A%E9%80%9A%E7%94%A8%E5%AF%B9%E8%B4%A6%E4%B8%AD%E5%BF%83/" title="系统设计：通用对账中心">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">系统设计：通用对账中心</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/07/01/%E7%94%9F%E4%BA%A7%E4%BA%8B%E6%95%85%EF%BC%9ARocketMQ%E6%B6%88%E6%81%AF%E4%BD%93%E5%A4%A7%E5%B0%8F%E8%B6%85%E5%87%BA%E9%99%90%E5%88%B6/" title="生产事故：RocketMQ消息体大小超出限制">
                        <span class="hidden-mobile">生产事故：RocketMQ消息体大小超出限制</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"fwhgdRnxBMBQuwXd6G2KY7uA-gzGzoHsz","appKey":"wz9qgHwvuMw8Y0yXAvL1KEr4","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script  src="https://lib.baomitu.com/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.js" ></script>

  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
